// Service Worker for TodoList PWA
const CACHE_NAME = 'todolist-v1.0.0';
const urlsToCache = [
  './todolist.html',
  './manifest.json',
  'https://cdn.tailwindcss.com/3.3.3',
  'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css',
  'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js'
];

// 安装事件 - 缓存资源
self.addEventListener('install', event => {
  console.log('Service Worker: 安装中...');
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => {
        console.log('Service Worker: 缓存文件');
        return cache.addAll(urlsToCache);
      })
      .then(() => self.skipWaiting()) // 立即激活新的service worker
  );
});

// 激活事件 - 清理旧缓存
self.addEventListener('activate', event => {
  console.log('Service Worker: 激活中...');
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cacheName => {
          if (cacheName !== CACHE_NAME) {
            console.log('Service Worker: 删除旧缓存', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    }).then(() => self.clients.claim()) // 立即控制所有页面
  );
});

// 拦截请求 - 缓存优先策略
self.addEventListener('fetch', event => {
  // 跳过非GET请求
  if (event.request.method !== 'GET') return;
  
  // 跳过chrome extension请求
  if (event.request.url.startsWith('chrome-extension://')) return;
  
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        // 缓存命中 - 返回缓存的资源
        if (response) {
          console.log('Service Worker: 从缓存返回', event.request.url);
          return response;
        }
        
        // 缓存未命中 - 从网络获取
        console.log('Service Worker: 从网络获取', event.request.url);
        return fetch(event.request).then(response => {
          // 检查是否是有效的响应
          if (!response || response.status !== 200 || response.type === 'error') {
            return response;
          }
          
          // 克隆响应 - 因为响应只能使用一次
          const responseToCache = response.clone();
          
          // 将新资源添加到缓存
          caches.open(CACHE_NAME).then(cache => {
            cache.put(event.request, responseToCache);
          });
          
          return response;
        });
      })
      .catch(error => {
        console.error('Service Worker: 获取失败', error);
        // 可以在这里返回一个离线页面
        return new Response('离线模式：无法加载资源', {
          status: 503,
          statusText: 'Service Unavailable',
          headers: new Headers({
            'Content-Type': 'text/plain'
          })
        });
      })
  );
});

// 监听消息事件 - 用于手动清除缓存
self.addEventListener('message', event => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
  
  if (event.data && event.data.type === 'CLEAR_CACHE') {
    event.waitUntil(
      caches.keys().then(cacheNames => {
        return Promise.all(
          cacheNames.map(cacheName => {
            return caches.delete(cacheName);
          })
        );
      }).then(() => {
        return self.registration.unregister();
      }).then(() => {
        return self.clients.matchAll();
      }).then(clients => {
        clients.forEach(client => client.navigate(client.url));
      })
    );
  }
});

// 同步事件 - 用于后台同步（可选）
self.addEventListener('sync', event => {
  if (event.tag === 'sync-tasks') {
    console.log('Service Worker: 后台同步任务');
    // 在这里可以添加后台同步逻辑
  }
});

// 推送通知（可选，需要用户授权）
self.addEventListener('push', event => {
  const options = {
    body: event.data ? event.data.text() : '您有新的任务提醒',
    icon: './icon-192.png',
    badge: './icon-192.png',
    vibrate: [200, 100, 200],
    tag: 'todolist-notification'
  };

  event.waitUntil(
    self.registration.showNotification('TodoList 提醒', options)
  );
});

// 通知点击事件
self.addEventListener('notificationclick', event => {
  event.notification.close();
  
  event.waitUntil(
    clients.openWindow('./todolist.html')
  );
});

